<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>组合模式实现多层列表生成</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
  <script>
    class ListItem {
      constructor(id) {
        this.id = id;
      }

      subListItems = [];

      addSubListItem(subListItem) {
        this.subListItems.push(subListItem);
      }

      removeSubListItem(id) {
        this.subListItems = this.subListItems.filter((item) => item !== id);
      }

      render(container){
        const ul = document.createElement("ul")
        container.appendChild(ul)
        this.subListItems.forEach(item => {
            const li = document.createElement("li")
            li.innerHTML = item.id
            item.render(li)
            ul.appendChild(li)
        });
      }
    }

    const root = new ListItem('root')
    const itemA = new ListItem('A')
    const itemB = new ListItem('B')
    const itemC = new ListItem('C')
    const itemA1 = new ListItem('A1')
    const itemA2 = new ListItem('A2')
    const itemA3 = new ListItem('A3')
    const itemB1 = new ListItem('B1')
    const itemB2 = new ListItem('B2')
    const itemC1 = new ListItem('C1')

    root.addSubListItem(itemA)
    root.addSubListItem(itemB)
    root.addSubListItem(itemC)

    itemA.addSubListItem(itemA1)
    itemA.addSubListItem(itemA2)
    itemA.addSubListItem(itemA3)

    itemB.addSubListItem(itemB1)
    itemB.addSubListItem(itemB2)

    itemC.addSubListItem(itemC1)
    // 在根节点上渲染数据
    root.render(document.querySelector("#root"))

  </script>
</html>
